package com.zmj.sy.mom.srv.aps.service.scheduler.extractor;

import cn.hutool.core.lang.Assert;
import com.zmj.sy.mom.srv.aps.bean.entity.order.OrderPhase;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.Group;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.Phase;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.Station;
import com.zmj.sy.mom.srv.aps.mapper.GroupMapper;
import com.zmj.sy.mom.srv.aps.mapper.PhaseMapper;
import com.zmj.sy.mom.srv.aps.mapper.StationMapper;
import com.zmj.sy.mom.srv.aps.service.scheduler.inverted.InvertedScheduleContext;
import com.zmj.sy.mom.srv.aps.service.scheduler.inverted.InvertedScheduleOrder;
import com.zmj.sy.mom.srv.aps.service.scheduler.order.DefaultOrder;
import com.zmj.sy.mom.srv.aps.service.scheduler.order.DefaultPhase;
import com.zmj.sy.mom.srv.aps.service.scheduler.resource.DefaultFactory;
import com.zmj.sy.mom.srv.aps.utils.SyExceptionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class FactoryExtractor {

    private final GroupMapper groupMapper;

    private final StationMapper stationMapper;

    private final PhaseMapper phaseMapper;

    public DefaultFactory load(InvertedScheduleContext context, InvertedScheduleOrder order) {
        DefaultFactory factory = new DefaultFactory();

        Set<String> workGroupNumbers = order.getOrders().stream()
                .map(DefaultOrder::getPhaseList)
                .flatMap(Collection::stream)
                .map(DefaultPhase::getPhase)
                .map(OrderPhase::getWorkGroupNumber)
                .filter(StringUtils::hasText)
                .collect(Collectors.toSet());
        Assert.notEmpty(workGroupNumbers, "BOM 未提供工作组信息");

        List<Group> groups = groupMapper.lambdaQuery()
                .in(Group::getMyCode, workGroupNumbers)
                .list();
        if (groups.isEmpty()) {
            throw SyExceptionUtils.e("工作组信息未配置" + workGroupNumbers);
        }
        factory.setGroups(groups);

        List<Station> stations = stationMapper.lambdaQuery()
                .in(Station::getGroupId, factory.groupIds()).list();
        factory.setStations(stations);

        List<Phase> phases = phaseMapper.lambdaQuery()
                .list();
        factory.setPhases(phases);

        return factory;
    }

}
